import axios, { AxiosError, type AxiosInstance, type AxiosResponse, type InternalAxiosRequestConfig }from 'axios'
import { ElMessage } from 'element-plus'
import errorCode from '@/utils/errorCode'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000
})

// 字段映射规则（前端字段 -> 后端字段）
const FIELD_MAPPING = {
  tableId: 'diningTableId',    // 前端字段 -> 后端字段
  tableStatus: 'status',        // 前端字段 -> 后端字段
  // 可添加更多映射规则...
  categoryId: 'dishClassificationId',
  categoryName: 'dishCategory',
  dishPrice: 'price',
  category: 'dishCategory',
  intro: 'introductionToDishes',
  tasteId: 'dishTasteId',
  tasteName: 'description',
  orderAmount: 'total',
  orderStatus: 'status',
  receivedAmount: 'actualPay',
  value: 'ticketPrice',
  packageName: 'setMenu',
  packagePrice: 'setmealPrice',
  description: 'setmealDescription',
  createTime: 'createdAt',
  updateTime: 'updatedAt',
  discountAmount: 'discount'
}

// 对象键名转换工具函数
const transformKeys = (obj: any, mapping: Record<string, string>, deep = false): any => {
  if (!obj || typeof obj !== 'object') return obj

  // 处理数组
  if (Array.isArray(obj)) {
    return obj.map(item => transformKeys(item, mapping, deep))
  }

  const result = { ...obj }
  Object.entries(mapping).forEach(([oldKey, newKey]) => {
    if (obj.hasOwnProperty(oldKey)) {
      result[newKey] = obj[oldKey]
      delete result[oldKey]
    }
  })

  // 递归处理嵌套对象
  if (deep) {
    Object.keys(result).forEach(key => {
      if (typeof result[key] === 'object' && result[key] !== null) {
        result[key] = transformKeys(result[key], mapping, deep)
      }
    })
  }

  return result
}

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {

    // 跳过标记的特殊请求
    if (config.data?.__noTransform) {
      delete config.data.__noTransform
      return config
    }

    // 转换GET请求参数（params）
    if (config.params) {
      config.params = transformKeys(config.params, FIELD_MAPPING)
    }

    // 转换POST/PUT请求数据（data）
    if (config.data) {
      config.data = transformKeys(config.data, FIELD_MAPPING)
    }

    return config
  },
  (error: AxiosError) => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (res: AxiosResponse) => {
    const code: number = res.data.code || 200
    const msg = errorCode[code] || res.data.msg
    if (code === 200) {
      const transformedData = transformKeys(res.data, {
        diningTableId: 'tableId',    // 后端字段 -> 前端字段
        status: 'tableStatus',        // 后端字段 -> 前端字段
        dishClassificationId: 'categoryId',
        dishCategory: 'categoryName',
        price: 'dishPrice',
        introductionToDishes: 'intro',
        dishTasteId: 'tasteId',
        description: 'tasteName',
        total: 'orderAmount',
        // status: 'orderStatus',
        actualPay: 'receivedAmount',
        ticketPrice: 'value',
        setMenu: 'packageName',
        setmealPrice: 'packagePrice',
        setmealDescription: 'description',
        createdAt: 'createTime',
        updatedAt: 'updateTime',
        discount: 'discountAmount'

      }, true) // true表示递归转换嵌套对象

      return Promise.resolve(transformedData)
    } else {
      ElMessage({ message: msg, type: 'error' })
      return Promise.reject(new Error(msg))
    }
  },
  (error: AxiosError) => {
    console.log('err' + error)
    let { message } = error
    if (message == 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    ElMessage({ message: message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)

export default service